package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author lwd
 * @since 2023-04-24
 */
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;


    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //0、校验地址是否存在、校验购物车是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (ObjectUtils.isEmpty(addressBook)) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart params = ShoppingCart.builder().userId(userId).build();
        final List<ShoppingCart> cartList = shoppingCartMapper.queryByParmas(params);
        if (ObjectUtils.isEmpty(cartList)) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1、组装Orders，保存至Orders表
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(Long.valueOf(System.currentTimeMillis()).toString());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setUserName(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());

        this.ordersMapper.save(orders);

        //2、根据购物车，组装OrderDetails List，保存至OrderDetail表（N条数据）
        List<OrderDetail> orderDetails = new ArrayList<>();
        cartList.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });
        this.orderDetailMapper.batchSave(orderDetails);

        //3、清空购物车
        this.shoppingCartMapper.clean(userId);

        //4、组装OrderSubmitVO并返回
        final OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 完成订单
     * zhongweiwei
     *
     * @param id
     */
    @Override
    public void CompleteOrder(Long id) {
        //1-判断当前订单是否存在
        Orders orders = ordersMapper.getByOrderId(id);
        if (ObjectUtils.isEmpty(orders)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2-验证当前用户是否有权限修改订单状态
//        Long currentId = BaseContext.getCurrentId();
//        User user = User.builder()
//                .id(currentId)
//                .build();
//
//        if (!user.getId().equals(orders.getUserId())){
//            throw new OrderBusinessException("当前用户没权限修改订单");
//        }
        // TODO: 2023/4/25 不知道为什么所有操做都没权限了，所以我打算注释掉
        //3-修改订单状态
        orders.setStatus(Orders.COMPLETED);
        //4-修改订单表数据
        ordersMapper.update(orders);

    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void CancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders order = new Orders();
        //3-赋值
        BeanUtils.copyProperties(ordersCancelDTO, order);


        //1-判断当前订单是否存在
        Orders orders = ordersMapper.getByOrderId(order.getId());
        if (ObjectUtils.isEmpty(orders)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2-验证当前用户是否有权限修改订单状态
//        Long id = BaseContext.getCurrentId();
//        User user = User.builder()
//                .id(id)
//                .build();
//        if (!user.getId().equals(orders.getUserId())) {
//            throw new OrderBusinessException("当前用户没权限修改订单");
//
//        }
        // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        // TODO: 2023/4/25 不知道为什么所有操做都没权限了，所以我打算注释掉
        if (order.getStatus() == Orders.COMPLETED) {
            //现实点单尝试，如果订单已送达，取消订单按钮会消失
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //3-修改订单状态
        orders.setStatus(Orders.CANCELLED);
        //放入处理订单理由
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        //4-修改订单表数据
        ordersMapper.update(orders);

    }

    /**
     * 统计各个状态的订单数量
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statisticsOrder() {
        OrderStatisticsVO vo = ordersMapper.statisticsOrder();
        return vo;
    }

    /**
     * 拒绝订单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO, order);
        //1-判断当前订单是否存在
        Orders orders = ordersMapper.getByOrderId(order.getId());
        if (ObjectUtils.isEmpty(orders)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //3-修改订单状态
        orders.setStatus(Orders.CANCELLED);
        //放入处理订单理由
        orders.setCancelReason(orders.getCancelReason());
        //4-修改订单表数据
        ordersMapper.update(orders);

    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO, order);
        //1-判断当前订单是否存在
        Orders orders = ordersMapper.getByOrderId(order.getId());
        if (ObjectUtils.isEmpty(orders)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //3-修改订单状态
        orders.setStatus(Orders.CONFIRMED);
        //4-修改订单表数据
        ordersMapper.update(orders);

    }

    /**
     * 派送订单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void deliveryOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO, order);
        //1-判断当前订单是否存在
        Orders orders = ordersMapper.getByOrderId(order.getId());
        if (ObjectUtils.isEmpty(orders)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //3-修改订单状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        //4-修改订单表数据
        ordersMapper.update(orders);

    }

    /**
     * 分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = ordersMapper.page(ordersPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * B/C查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO detailsOrder(Long id) {
        OrderVO orderVO = new OrderVO();
        //1-获取地址
        AddressBook addressBook = addressBookMapper.querById(id);
        BeanUtils.copyProperties(addressBook, orderVO);
        //2-获取订单菜品
        List<OrderDetail> orderVOList = orderDetailMapper.getbyidDish(id);
        orderVO.setOrderDetailList(orderVOList);
        //3-获取订单信息
        Orders orders = ordersMapper.getById(id);
        BeanUtils.copyProperties(orders, orderVO);
        return orderVO;
    }

    @Override
    public PageResult historyOrders(Integer page, Integer pagesize, Integer status) {
        //设置页数参数
        PageHelper.startPage(page, pagesize);
        //1-获取用户id
        Long userID = BaseContext.getCurrentId();
        //2查询订单
        Page<OrderVO> orderVOS = ordersMapper.historyOrders(userID, status);
        for (OrderVO vo : orderVOS) {
            List<OrderDetail> orderDetails = ordersMapper.historyOrdersDt(vo.getId());
            vo.setOrderDetailList(orderDetails);
        }

        //封装返回数据
        return new PageResult(orderVOS.getTotal(), orderVOS.getResult());

    }

    /**
     * C端取消订单
     *
     * @param id
     */
    @Override
    public void CancelOrders(Long id) {

        Orders order = new Orders();
        order.setId(id);

        //1-判断当前订单是否存在
        Orders orders = ordersMapper.getByOrderId(order.getId());
        if (ObjectUtils.isEmpty(orders)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //2判断订单状态
        if (order.getStatus() == Orders.COMPLETED) {
            //现实点单尝试，如果订单已送达，取消订单按钮会消失
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //3-修改订单状态
        orders.setStatus(Orders.CANCELLED);
        //4-修改订单表数据
        ordersMapper.update(orders);

    }

    /**
     * c端再来一单
     *
     * @param id
     */
    @Override
    public void repetitionOrder(Long id) {
        //1-查询之前订单的内容
        List<OrderDetail> orderDetails = ordersMapper.historyOrdersDt(id);
        Long userId = BaseContext.getCurrentId();
        //2-清空购物车
        shoppingCartMapper.clean(userId);
        //3-添加购物车
      ShoppingCart shoppingCart =new ShoppingCart();
      shoppingCart.setUserId(userId);
      shoppingCart.setCreateTime(LocalDateTime.now());
        for (OrderDetail orderDetail : orderDetails) {
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCartMapper.save(shoppingCart);

        }
    }
}


